package com.csthink.common.application.advice;

import com.csthink.common.application.ResponseWrapper;
import com.csthink.common.infrastructure.util.Jackson2Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Map;

/**
 * 全局响应处理类,将数据进行返回前进行增强操作
 *
 * @author <a href="mailto:security.2009@live.cn">Mars</a>
 * @since 2023-09-09
 */
@Slf4j
@RestControllerAdvice(basePackages = {"com.csthink.web.interfaces"})
public class GlobalResponseAdvice implements ResponseBodyAdvice<Object> {


    /**
     * 判断 beforeBodyWrite 方法是否会执行,true: 执行, false: 放行
     * 不需要进行增强操作可以在 supports 方法里进行判断
     *
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        Class<?> targetClass = returnType.getMethod().getDeclaringClass();
        log.debug("supports execute methodParameter={} targetClass={} class={}", returnType, targetClass, converterType);
        // 如果接口返回的类型是 ResponseWrapper 则不做任何额外的处理
        return !returnType.getParameterType().equals(ResponseWrapper.class);
    }

    /**
     * 修改响应体，对返回的数据进行增强处理
     *
     * @param body
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        log.debug("beforeBodyWrite data={}", body);

        // 测试内容
        response.getHeaders().set("test-header", "test-value");

        if (null == body) {
            return ResponseWrapper.success();
        } else if (body instanceof ResponseWrapper) {
            return body;
        } else if (body instanceof String || String.class.equals(returnType.getGenericParameterType())) {
            // 若原返回结果为String，则转换为JSON响应体再返回
            response.getHeaders().set("Content-Type", "application/json");
            return Jackson2Util.toJson(ResponseWrapper.success(body));
        }

        return ResponseWrapper.success(body);
    }
}
